package com.community.common.interceptor;

import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.MyResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * OpenApi 统一鉴权
 */
@Aspect
@Component
public class OpenSecurityInterceptor {

    @Value("${open.securityKey}")
    private String securityKey;

    private static final String authHeader = "Authorization";

    @Pointcut("execution(* com.community.common.controller.OpenController.*(..))")
    public void cut(){

    }

    @Around("cut()")
    public Object check(ProceedingJoinPoint point) throws Throwable {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest)requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        String header = request.getHeader(authHeader);
        if (header == null || !header.equals(securityKey)) {
            return MyResponse.fail(CodeEnum.SYSTEM_NO_LOGIN);
        }
        return point.proceed();
    }

}
